package org.vacoor.xqq.ui.chat;

import com.google.common.eventbus.Subscribe;
import org.vacoor.xqq.Login3;
import org.vacoor.xqq.core.msg.chatmsg.ContactMsg;
import org.vacoor.xqq.hotkey.OSHotKeyEvent;
import org.vacoor.xqq.hotkey.OSHotKeyListener;
import org.vacoor.xqq.hotkey.OSHotKeyManager;
import org.vacoor.xqq.ui.dynamictree.Buddy;
import org.vacoor.xqq.ui.dynamictree.BuddyNode;
import org.vacoor.xqq.ui.dynamictree.TreeNodeMouseEventListener;
import org.vacoor.xqq.ui.comp.trayicon.AppSysTrayIcon;
import org.vacoor.xqq.ui.comp.trayicon.TrayAnimatedIcon;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

/**
 * User: Vacoor
 */
public class MessageDispatcher {
    private final Object lock = new Object();
    private ConcurrentHashMap<Long, Vector<ContactMsg>> msgStack = new ConcurrentHashMap<Long, Vector<ContactMsg>>();
    private Buddy lastBuddy;
    private ChatManager chatManager;
    private UIBuddyManager buddyManager;

    public MessageDispatcher(ChatManager chatManager, UIBuddyManager buddyManager) {
        this.chatManager = chatManager;
        this.buddyManager = buddyManager;
        init();
    }

    public void init() {

        TreeNodeMouseEventListener nodeHandler = new TreeNodeMouseEventListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JTree tree = (JTree) e.getSource();
                TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                if (null == path || !SwingUtilities.isLeftMouseButton(e) || e.getClickCount() < 2) {
                    return;
                }

                Object node = tree.getLastSelectedPathComponent();
                if (!(node instanceof BuddyNode)) {
                    return;
                }
                BuddyNode n = (BuddyNode) node;
                openChat(n.getData());
                TrayAnimatedIcon trayIcon = AppSysTrayIcon.getCurrentAppTrayAnimatedIcon();
                if(trayIcon != null) {
                    trayIcon.removeAnimation((int) n.getData().getId());
                }
                lastBuddy = null;
            }
        };
        nodeHandler.bind(buddyManager.buddies);

        //
        OSHotKeyManager hotKeyManager = OSHotKeyManager.getCurrentOSHotKeyManager();
        if(hotKeyManager != null) {
            hotKeyManager.getOSHotKeyBinder(Login3.OS_SHOW_IDENTIFER).addOSHotKeyListener(new OSHotKeyListener() {
                @Override
                public void onOSHotKey(OSHotKeyEvent event) {
                    if(lastBuddy == null) {
                        Window window = SwingUtilities.windowForComponent(buddyManager.buddies);
                        if(window != null && window instanceof Frame) {
                            Frame f = (Frame) window;
                            f.setVisible(!f.isActive());
                        }
                        return;
                    }
                    openChat(lastBuddy);
                    TrayAnimatedIcon trayIcon = AppSysTrayIcon.getCurrentAppTrayAnimatedIcon();
                    if(trayIcon != null) {
                        trayIcon.removeAnimation((int) lastBuddy.getId());
                    }
                    lastBuddy = null;
                }
            });
        }
    }

    @Subscribe
    public void onMsg(ContactMsg msg) {
        final long cid = msg.getFromUin();
        Buddy buddy = buddyManager.getBuddy(cid);

        Chat chat = chatManager.getChat(buddy, false);

        // 如果不在聊天列表中, 将压入消息栈, 并唤醒
        if (chat == null) {
            pushMsg(msg);
            buddyManager.notifyUser(buddy.getId());
            lastBuddy = buddy;
            TrayAnimatedIcon trayIcon = AppSysTrayIcon.getCurrentAppTrayAnimatedIcon();
            if(trayIcon != null) {
                trayIcon.addFlashAnimation((int) lastBuddy.getId(), ((ImageIcon)lastBuddy.getAvatar()).getImage(), false);
            }
        } else {
            chat.writeContactMsg(msg);
            chatManager.notifyUser(chat);
            lastBuddy = null;
        }
    }


    public void pickUpMsgAndOpenChat() {
    }

    /**
     * 打开与给定联系人的 Chat, 如果需要则创建新 Chat
     */
    public synchronized void openChat(Buddy buddy) {
        Chat chat = chatManager.getChat(buddy, true);
        Vector<ContactMsg> contactMsgs = pickUpMsg(buddy.getId());
        for (ContactMsg m : contactMsgs) {
            chat.writeContactMsg(m);
        }
        chatManager.setCurrentChat(chat);
        buddyManager.cancelNotify(buddy.getId());
    }

    public Vector<ContactMsg> pickUpMsg(long cid) {
        Vector<ContactMsg> contactMsgs = msgStack.remove(cid);
        if (contactMsgs == null) {
            contactMsgs = new Vector<ContactMsg>();
        }
        return contactMsgs;
    }

    protected void pushMsg(ContactMsg msg) {
        final long fid = msg.getFromUin();
        Vector<ContactMsg> fmsg = msgStack.get(fid);
        synchronized (lock) {
            if (fmsg == null) {
                fmsg = new Vector<ContactMsg>();
                msgStack.put(fid, fmsg);
            }
        }
        fmsg.add(msg);
    }
}
